package com.hrp.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * Created by Administrator on 2018/8/7 0007.
 */
@Controller
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping("/login")
    public String login(@ModelAttribute("message") String message, Model model){
        return "login";
    }
    @RequestMapping("/loginUser")
    @ResponseBody
    public String loginUser(String username, String password, HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        UsernamePasswordToken token  =new UsernamePasswordToken(username,password);
        //获取当前的Subject
        Subject currentUser = SecurityUtils.getSubject();
        try {
            //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
            //每个Realm都能在必要时对提交的AuthenticationTokens作出反应
            //所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
            currentUser.login(token);
        }catch(UnknownAccountException uae){
            //logger.info("对用户[" + username + "]进行登录验证..验证未通过,未知账户");
            return "false";
        }catch(IncorrectCredentialsException ice){
            //logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");
            return "false";
        }catch(LockedAccountException lae){
            //logger.info("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");
            return "false";
        }catch(ExcessiveAttemptsException eae){
            //logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多");
            return "false";
        }catch(AuthenticationException ae){
            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
            //logger.info("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");
            return "false";
        }
        //验证是否登录成功
        if(currentUser.isAuthenticated()){
            //logger.info("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
            return "true";
        }else{
            token.clear();
            return "false";
        }
    }


    @RequestMapping("/logOut")
    public String logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
//        session.removeAttribute("user");
        return "login";
    }
}
